// Problem 042: Coded triangle numbers
// The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
// 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
// By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
// Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words?

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
)

func p042() {
	fp, err := os.Open("./data/p042_words.txt")
	if err != nil {
		panic("p042_words.txt not found.")
	}
	defer fp.Close()
	var words []string
	reader := bufio.NewReader(fp)
	for {
		line, err := reader.ReadString(',')
		if err != nil {
			if err == io.EOF {
				words = append(words, line[1:len(line)-1])
				break
			}
			panic("Error in read file p022_words.txt.")
		}
		words = append(words, line[1:len(line)-2])
	}
	ans := 0
	for _, word := range words {
		wv := wordValue(word)
		if inSeq(wv) {
			ans++
		}
	}
	fmt.Println("Problem 042:", ans)
}

func wordValue(name string) (total int) {
	for _, c := range name {
		total += int(c - 64)
	}
	return total
}

func inSeq(v int) bool {
	n := int(math.Sqrt(float64(2 * v)))
	for ; n*(n+1) > 2*v; n-- {
	}
	return n*(n+1) == 2*v
}
